﻿using System;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace PowerApp
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;

            this.exitbutton9.Click += delegate (object obj, EventArgs ev)
            {
                Application.Exit();
            };

            base.OnLoad(e);
        }
        protected override void OnClosed(EventArgs e)
        {
            ClosePort();

            base.OnClosed(e);
        }


        [DllImport("Port.dll", CharSet = CharSet.Auto)]
        public extern static int OpenPort(int num, int bps, int dataBits, int parity, int stopBits, IntPtr hwnd);

        [DllImport("Port.dll", CharSet = CharSet.Auto)]
        public extern static int ClosePort();

        [DllImport("Port.dll", CharSet = CharSet.Auto)]
        public extern static int GetError();

        [DllImport("Port.dll", CharSet = CharSet.Auto)]
        public extern static int Connect(int channel, int count);

        [DllImport("Port.dll", CharSet = CharSet.Auto)]
        public extern static int Disconnect(int channel, int count);

        // 打开串口对话框
        OpenComForm2 cf = null;
        OpenComForm2 ComDlg
        {
            get
            {
                if (cf == null)
                {
                    cf = new OpenComForm2();
                }

                return cf;
            }
        }

        bool PortOpen
        {
            get { return opencombutton1.Text == "关闭串口"; }
        }

        const int channelCount = 10;
        private void opencombutton1_Click(object sender, EventArgs e)
        {
            if (!PortOpen)
            {
                if (ComDlg.ShowDialog() == DialogResult.Cancel) return;

                Debug.Print("Num:{0} BPS:{1} DataBits:{2} Parity:{3} StopBits:{4}", ComDlg.Num, ComDlg.BPS, ComDlg.DataBits, ComDlg.Parity, ComDlg.StopBits);

                if (OpenPort(ComDlg.Num, ComDlg.BPS, ComDlg.DataBits, ComDlg.Parity, ComDlg.StopBits, this.Handle) == 0) // success
                {
                    opencombutton1.Text = "关闭串口";

                    infolabel1.Text = string.Format("COM{0} 已经打开", ComDlg.Num);

                    connectbutton2.Enabled = true;
                }
                else
                {
                    ClosePort();

                    BigMsgBox.Show(string.Format("打开串口出错\n错误{0}", GetError()), "串口操作", MessageBoxButtons.OK);
                }
            }
            else
            {
                if (BigMsgBox.Show("确定要关闭串口？", "串口操作", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    ClosePort();

                    opencombutton1.Text = "打开串口";

                    infolabel1.Text = "请先打开串口";

                    connectbutton2.Enabled = false;
                    disconnectbutton3.Enabled = false;
                }
            }
        }


        private void connectbutton2_Click(object sender, EventArgs e)
        {
            ChannelForm2 chDlg = new ChannelForm2();

            if (chDlg.ShowDialog() == DialogResult.Cancel) return;

            var selectArray = chDlg.SelectedChannels;

            for (int i = 0; i < selectArray.Length; i++)
            {
                if(selectArray[i])
                {
                    //Connect(i);
                }

                Debug.Print("{0}: {1}", i + 1, selectArray[i] ? "Y" : " ");
            }

        }

        private void disconnectbutton3_Click(object sender, EventArgs e)
        {
            ChannelForm2 chDlg = new ChannelForm2();

            if (chDlg.ShowDialog() == DialogResult.Cancel) return;

            var selectArray = chDlg.SelectedChannels;

            for (int i = 0; i < selectArray.Length; i++)
            {
                if (selectArray[i])
                {
                    //Disconnect(i);
                }

                Debug.Print("{0}: {1}", i + 1, selectArray[i] ? "Y" : " ");
            }
        }

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
        }

        private void openparabutton4_Click(object sender, EventArgs e)
        {
            // 这个对话框字体太小
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Multiselect = true;
            ofd.Title = "打开参数";
            ofd.Filter = "参数文件|*.par";

            if (ofd.ShowDialog() == DialogResult.Cancel) return;

            if (Debugger.IsAttached)
            {
                if (MessageBox.Show("Settings.Default.Reset()?", "", MessageBoxButtons.OKCancel) == DialogResult.OK)
                {
                    PowerApp.Properties.Settings.Default.Reset();
                }
            }

            bool changed = false;
            StringCollection parafiles = PowerApp.Properties.Settings.Default.ParFiles;

            for (int i = 0; i < ofd.FileNames.Length; i++)
            {
                if (!parafiles.Contains(ofd.FileNames[i]))
                {
                    parafiles.Add(ofd.FileNames[i]);

                    changed = true;

                    Debug.Print(ofd.FileNames[0]);
                }

            }

            if (changed) PowerApp.Properties.Settings.Default.Save();

        }

        private void sendparabutton5_Click(object sender, EventArgs e)
        {

        }
    }
}
